package com.yumao.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/1.
 */

public class MyAdapter2 extends RecyclerView.Adapter<MyAdapter2.ViewHolder> {

    private LayoutInflater inflater;
    private List<String> list;
    private List<Integer> heightList;
    private RecyclerClickListener listener;

    public MyAdapter2(Context context, List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
        heightList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            int height = (int) (Math.random() * 300 + 200);
            heightList.add(height);
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.recycler_item2, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final int p = holder.getLayoutPosition();
        holder.textView.setText(list.get(p));
        holder.textView.getLayoutParams().height = heightList.get(position);
        if (listener != null) {
            holder.textView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    listener.onLongClick(position, p);
                    return true;
                }
            });
            holder.textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.onClick(position, p);
                }
            });
        }
    }

    public void delete(int position, int layoutPosition) {
        list.remove(layoutPosition);
        heightList.remove(layoutPosition);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void setListener(RecyclerClickListener listener) {
        this.listener = listener;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }

    public interface RecyclerClickListener {
        void onClick(int position, int layoutPosition);

        void onLongClick(int position, int layoutPosition);
    }
}
